<?php

namespace App\Services\Registration;

use App\Models\CompanyModel;
use App\Models\RegistrationRechargeModel;
use App\Models\RegistrationLogModel;
use Illuminate\Support\Facades\DB;


class RegistrationService
{
    // 充值报名单
    public static function recharge(int $companyId, int $num,$operate_at, string $remark = '')
    {
        return DB::transaction(function () use ($companyId,$num,$remark,$operate_at) {
            $company = CompanyModel::query()->findOrFail($companyId);
            // 插入充值日志
            RegistrationRechargeModel::query()->create([
                'company_id' => $company->id,
                'num' => $num,
                'amount' => 0,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            // 插入变更日志
            return self::changeRegistrationNum($companyId, $num,$operate_at, $remark);
        });
    }

    /**
     * 增加或减少
     * @param int $companyId
     * @param int $changeNum
     * @param $operate_at
     * @param string $remark
     * @return false|mixed
     */
    public static function changeRegistrationNum(int $companyId, int $changeNum,$operate_at, string $remark = '')
    {
        if ($changeNum == 0) return false;
           return DB::transaction(function () use ($companyId, $changeNum, $remark,$operate_at) {
                // 找到商家
                $company = CompanyModel::query()->findOrFail($companyId);
                $beforeNum = $company->registration_num;
                // 判断变动类型是增加还是减少
                if ($changeNum > 0) {
                    $company->registration_num += abs($changeNum);
                } elseif ($changeNum < 0) {
                    $company->registration_num -= abs($changeNum);
                }
                // 保存变动后的报名单余额
                $company->save();
                // 插入变更日志
                $res = RegistrationLogModel::query()->create([
                    'company_id' => $companyId,
                    'before_num' => $beforeNum,
                    'change_num' => abs($changeNum),
                    'after_num' => $company->registration_num,
                    'operate_at' => $operate_at,
                    'cur_type' => $changeNum > 0 ? 'add' : 'cut',
                    'remark' => $remark,
                ]);
                return $res;
            });
    }
}
